import { Table } from 'antd';
import Cls from 'classnames';
import { useContext, useEffect, useMemo } from 'react';
import { AcquisitionManageContext, IAcquisitionActionEnum } from '../mconfig';
import { materialTableColumn } from '../mconfig/MaterialTableColumn';
import { formatDecimalFour, formatDecimal } from '@/pages/AssetManage/Acommon';

/** 领用/退库 表单第三项-材料列表 */
export const MaterialTableView: React.FC<any> = ({ openMaterialModalFun, pageType, loadMapInfo, mapLoading, queryType, editState }) => {
  const { materialList, acquisitionDispatch } = useContext(AcquisitionManageContext);

  // 取消选择的资产
  const delSelectRow = (record) => {
    const arr = materialList.filter((item) => {
      return item.id !== record.id;
    });
    acquisitionDispatch({
      type: IAcquisitionActionEnum.CANCEL_MATERIAL,
      payload: arr,
    });
  };

  /** 表格行配置 */
  const getTable: any = useMemo(() => {
    return materialTableColumn({ openMaterialModalFun, delSelectRow, pageType, loadMapInfo, mapLoading, queryType, editState });
  }, [materialList, queryType, editState]);

  const allPrice = useMemo(() => {
    const f: boolean = pageType == 'detail' && !editState;
    let val = 0;
    if (materialList?.length) {
      materialList?.forEach((item) => {
        if (f) {
          val += (Number(item?.expectNum) + Number(item?.quantityOrArea)) * Number(item?.assetValue);
        } else {
          val += Number(item?.residueNum) * Number(item?.assetValue);
        }
      });
    }
    return val;
  }, [materialList, pageType, editState]);

  return (
    <>
      <div className={Cls('list-table', 'descriptionsType-tableSty')}>
        <Table
          columns={getTable}
          bordered
          size="small"
          dataSource={materialList}
          scroll={{ x: 1200, y: '' }}
          pagination={false}
          rowKey={(res) => res?.materialOrAssetId}
        />
        <div style={{ textAlign: 'right', marginBottom: '10px' }}>合计：{formatDecimal(allPrice) || '0.0000'}</div>
      </div>
    </>
  );
};
